﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Runtime;
using System.Security.Claims;
using System.Text;
using Test.Entity;
using Test.Interface;

namespace Test.Service
{
    public class JwtHelperAppService : IJwtHelperAppService
    {
        private readonly IOptionsSnapshot<JWTTokenOption> _jwtTokenOption;

        public JwtHelperAppService(IOptionsSnapshot<JWTTokenOption> jwtTokenOption)
        {
            _jwtTokenOption = jwtTokenOption;
        }

        public string CreateToken()
        {
            // 1. 定义需要使用到的Claims
            var claims = new List<Claim>
            {
            new Claim(ClaimTypes.Name, "u_admin"),
            new Claim(ClaimTypes.Role, "A"),
            new Claim(JwtRegisteredClaimNames.Jti, "admin"),
            };
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtTokenOption.Value.IssuerSigningKey));
            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;
            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);
            // 5. 根据以上，生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _jwtTokenOption.Value.Issuer,     //Issuer
                _jwtTokenOption.Value.Audience,   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
               DateTime.Now.AddMinutes(_jwtTokenOption.Value.AccessTokenExpiresMinutes),    //expires
                signingCredentials               //Credentials
            );
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            return token;
        }
    }
}
